package com.horay.springbootdemo.web.servlet.common.controller;

import com.alibaba.fastjson.JSON;
import com.horay.springbootdemo.web.servlet.common.result.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * BaseServlet
 *
 * @author heyingcheng
 * @date 2019/9/11 1:15
 */
@Slf4j
public abstract class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doData(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doData(req, resp);
    }

    @Override
    public void init() throws ServletException {
        WebApplicationContextUtils.getWebApplicationContext(getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);
    }

    /**
     * 执行操作方法
     *
     * @param requestBody 请求消息体
     * @return java.lang.Object
     * @author heyingcheng
     * @date 2019/9/12 13:56
     */
    protected abstract Object execute(String requestBody);

    private void doData(HttpServletRequest request, HttpServletResponse response) {
        String requestBody = StringUtils.EMPTY;
        try {
            requestBody = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("RequestURL:[{}], request parameter exception, requestBody:[{}]", request.getRequestURL(), requestBody, e);
        }

        Object object = execute(requestBody);
        String resultData = StringUtils.EMPTY;
        if (object instanceof ResultBody) {
            resultData = JSON.toJSONString(object);
        } else {
            resultData = String.valueOf(object);
        }

        try {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            IOUtils.write(resultData, response.getOutputStream(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("RequestURL:[{}], response message exception, resultData:[{}]", resultData, e);
        }
    }

}
